# app/core/oss_service.py

import os
import uuid
import logging
from typing import Optional, Dict, Any
from datetime import datetime

import oss2
from config.settings import settings

logger = logging.getLogger(__name__)

class OSSService:
    """阿里云OSS服务类"""
    
    def __init__(self):
        """初始化OSS服务"""
        self.access_key_id = settings.ALIYUN_OSS_ACCESS_KEY_ID
        self.access_key_secret = settings.ALIYUN_OSS_ACCESS_KEY_SECRET
        self.region = settings.ALIYUN_OSS_REGION
        self.bucket_dataset = settings.ALIYUN_OSS_BUCKET_DATASET
        self.bucket_study = settings.ALIYUN_OSS_BUCKET_STUDY
        
        # 初始化OSS认证
        self.auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        
        # 初始化Bucket
        self.endpoint = f"https://{self.region}.aliyuncs.com"
        self.bucket_dataset_obj = oss2.Bucket(self.auth, self.endpoint, self.bucket_dataset)
        self.bucket_study_obj = oss2.Bucket(self.auth, self.endpoint, self.bucket_study)
        
        logger.info("OSS服务初始化完成")
    
    def upload_file(self, file_path: str, file_type: str, knowledge_base: str = "default") -> Dict[str, Any]:
        """
        上传文件到阿里云OSS
        
        Args:
            file_path: 本地文件路径
            file_type: 文件类型 (document, image, video, text)
            knowledge_base: 知识库名称
            
        Returns:
            包含上传结果的字典
        """
        try:
            if not os.path.exists(file_path):
                raise FileNotFoundError(f"文件不存在: {file_path}")
            
            # 生成OSS对象键
            file_name = os.path.basename(file_path)
            file_ext = os.path.splitext(file_name)[1]
            unique_id = str(uuid.uuid4())
            
            # 根据文件类型和知识库确定存储路径
            if file_type in ['document', 'text']:
                bucket = self.bucket_dataset_obj
                oss_key = f"documents/{knowledge_base}/{unique_id}{file_ext}"
            elif file_type == 'image':
                bucket = self.bucket_study_obj
                oss_key = f"images/{knowledge_base}/{unique_id}{file_ext}"
            elif file_type == 'video':
                bucket = self.bucket_study_obj
                oss_key = f"videos/{knowledge_base}/{unique_id}{file_ext}"
            else:
                bucket = self.bucket_dataset_obj
                oss_key = f"others/{knowledge_base}/{unique_id}{file_ext}"
            
            # 上传文件
            logger.info(f"开始上传文件到OSS: {file_path} -> {oss_key}")
            
            # 设置元数据
            metadata = {
                'original_filename': file_name,
                'file_type': file_type,
                'knowledge_base': knowledge_base,
                'upload_time': datetime.now().isoformat(),
                'file_size': str(os.path.getsize(file_path))
            }
            
            # 上传文件
            result = bucket.put_object_from_file(oss_key, file_path, headers=metadata)
            
            # 生成访问URL
            url = f"https://{bucket.bucket_name}.{self.region}.aliyuncs.com/{oss_key}"
            
            logger.info(f"文件上传成功: {url}")
            
            return {
                'success': True,
                'oss_key': oss_key,
                'url': url,
                'bucket': bucket.bucket_name,
                'file_size': os.path.getsize(file_path),
                'metadata': metadata
            }
            
        except Exception as e:
            logger.error(f"文件上传失败: {file_path}, 错误: {str(e)}")
            return {
                'success': False,
                'error': str(e),
                'file_path': file_path
            }
    
    def upload_file_from_bytes(self, file_bytes: bytes, file_name: str, file_type: str, knowledge_base: str = "default") -> Dict[str, Any]:
        """
        从字节数据上传文件到阿里云OSS
        
        Args:
            file_bytes: 文件字节数据
            file_name: 文件名
            file_type: 文件类型
            knowledge_base: 知识库名称
            
        Returns:
            包含上传结果的字典
        """
        try:
            # 生成OSS对象键
            file_ext = os.path.splitext(file_name)[1]
            unique_id = str(uuid.uuid4())
            
            # 根据文件类型和知识库确定存储路径
            if file_type in ['document', 'text']:
                bucket = self.bucket_dataset_obj
                oss_key = f"documents/{knowledge_base}/{unique_id}{file_ext}"
            elif file_type == 'image':
                bucket = self.bucket_study_obj
                oss_key = f"images/{knowledge_base}/{unique_id}{file_ext}"
            elif file_type == 'video':
                bucket = self.bucket_study_obj
                oss_key = f"videos/{knowledge_base}/{unique_id}{file_ext}"
            else:
                bucket = self.bucket_dataset_obj
                oss_key = f"others/{knowledge_base}/{unique_id}{file_ext}"
            
            # 设置元数据
            metadata = {
                'original_filename': file_name,
                'file_type': file_type,
                'knowledge_base': knowledge_base,
                'upload_time': datetime.now().isoformat(),
                'file_size': str(len(file_bytes))
            }
            
            # 上传文件
            result = bucket.put_object(oss_key, file_bytes, headers=metadata)
            
            # 生成访问URL
            url = f"https://{bucket.bucket_name}.{self.region}.aliyuncs.com/{oss_key}"
            
            logger.info(f"文件上传成功: {url}")
            
            return {
                'success': True,
                'oss_key': oss_key,
                'url': url,
                'bucket': bucket.bucket_name,
                'file_size': len(file_bytes),
                'metadata': metadata
            }
            
        except Exception as e:
            logger.error(f"文件上传失败: {file_name}, 错误: {str(e)}")
            return {
                'success': False,
                'error': str(e),
                'file_name': file_name
            }
    
    def delete_file(self, oss_key: str, bucket_name: str = None) -> Dict[str, Any]:
        """
        删除OSS中的文件
        
        Args:
            oss_key: OSS对象键
            bucket_name: 存储桶名称，如果为None则自动判断
            
        Returns:
            删除结果
        """
        try:
            if bucket_name:
                bucket = oss2.Bucket(self.auth, self.endpoint, bucket_name)
            else:
                # 根据oss_key判断使用哪个bucket
                if oss_key.startswith('documents/') or oss_key.startswith('others/'):
                    bucket = self.bucket_dataset_obj
                else:
                    bucket = self.bucket_study_obj
            
            bucket.delete_object(oss_key)
            logger.info(f"文件删除成功: {oss_key}")
            
            return {
                'success': True,
                'oss_key': oss_key
            }
            
        except Exception as e:
            logger.error(f"文件删除失败: {oss_key}, 错误: {str(e)}")
            return {
                'success': False,
                'error': str(e),
                'oss_key': oss_key
            }
    
    def get_file_url(self, oss_key: str, bucket_name: str = None, expires: int = 3600) -> str:
        """
        获取文件的临时访问URL
        
        Args:
            oss_key: OSS对象键
            bucket_name: 存储桶名称
            expires: 过期时间（秒）
            
        Returns:
            临时访问URL
        """
        try:
            if bucket_name:
                bucket = oss2.Bucket(self.auth, self.endpoint, bucket_name)
            else:
                # 根据oss_key判断使用哪个bucket
                if oss_key.startswith('documents/') or oss_key.startswith('others/'):
                    bucket = self.bucket_dataset_obj
                else:
                    bucket = self.bucket_study_obj
            
            url = bucket.sign_url('GET', oss_key, expires)
            return url
            
        except Exception as e:
            logger.error(f"获取文件URL失败: {oss_key}, 错误: {str(e)}")
            return ""
    
    def list_files(self, prefix: str = "", bucket_name: str = None) -> Dict[str, Any]:
        """
        列出指定前缀的文件
        
        Args:
            prefix: 文件前缀
            bucket_name: 存储桶名称
            
        Returns:
            文件列表
        """
        try:
            if bucket_name:
                bucket = oss2.Bucket(self.auth, self.endpoint, bucket_name)
            else:
                bucket = self.bucket_dataset_obj
            
            files = []
            for obj in oss2.ObjectIterator(bucket, prefix=prefix):
                files.append({
                    'key': obj.key,
                    'size': obj.size,
                    'last_modified': obj.last_modified
                })
            
            return {
                'success': True,
                'files': files,
                'count': len(files)
            }
            
        except Exception as e:
            logger.error(f"列出文件失败: {prefix}, 错误: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }

# 创建全局OSS服务实例
oss_service = OSSService() 